package com.apes.auto.autoparts.service;

import com.apes.auto.autoparts.model.EpcPartCodeParse;
import com.apes.auto.autoparts.repository.EpcPartCodeParseRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.logger.ApesLoggerService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.workflow.domain.CarbonCopyMessage;
import com.apes.framework.plugin.workflow.domain.CarbonCopyMessageRepository;
import com.apes.framework.util.MapUtil;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("epcPartCodeParseService")
public class EpcPartCodeParseService extends DomainService {

    @Autowired
    private EpcPartCodeParseRepository epcPartCodeParseRepository;
    @Autowired
    private CarbonCopyMessageRepository carbonCopyMessageRepository;
    @Autowired
    private ApesLoggerService apesLoggerService;
    /***
     * 创建
     */
    public EpcPartCodeParse create(SimpleRequest request) {

        EpcPartCodeParse epcPartCodeParse = request.getO(EpcPartCodeParse.class);


        // 去重（通过Epc版本）
        EpcPartCodeParse oldEpcPartCodeParse = epcPartCodeParseRepository.findOne(JpaDsl.toCriteriaByEq(
                "epcVersion", epcPartCodeParse.getEpcVersion(),
                "partCode", epcPartCodeParse.getPartCode(),
                "parseFlag", false
        )).orElse(null);
        if (oldEpcPartCodeParse != null) return oldEpcPartCodeParse;

        epcPartCodeParse = epcPartCodeParseRepository.saveAndFlush(epcPartCodeParse);

        // 推送代办
//        publishCarbonCopyMessage(epcPartCodeParse, request);

        if (epcPartCodeParse.isErrorFlag()) invoke("autoparts.epcPartCodeParse.deleteAll", MapUtil.mapped(epcPartCodeParse));


        return epcPartCodeParse;
    }


    /***
     * 编译
     */
    public Map parse(SimpleRequest request) {

        EpcPartCodeParse epcPartCodeParse = request.getO(EpcPartCodeParse.class);
        epcPartCodeParse.setParseFlag(true);

        // 处理待办数据
        updateAllCarbonCopyMessage(epcPartCodeParse);

        // 写入处理历史
        insertLogger(epcPartCodeParse, request);

        return MapUtil.mapped(epcPartCodeParseRepository.saveAndFlush(epcPartCodeParse)) ;
    }


    /***
     * 推送抄送消息
     * 推送本地角色： A0041
     */
//    public void publishCarbonCopyMessage(EpcPartCodeParse epcPartCodeParse, SimpleRequest request) {
//
//        // 获取所有需推送的用户
//        Post post = SpringManager.getBean(PostRepository.class).findOne("A0041");
//        List<Map> users = null;
//
//        for (User user : post.getAssignedUsers()) {
//            if (users == null) users = new ArrayList<>();
//            if (user.isDisable()) continue; // 去掉已离职的人员
//            users.add(MapUtil.mapper("id", user.getId()));
//        }
//        if (users.size() == 0) return;
//
//        User user = request.getCurrentUser();
//        Integer userId = request.getCurrentUser() != null ? user.getId() : 1;
//
//        sendSynEvent("event:wf.carbonCopy", mapper(
//                "sourceBusinessType", epcPartCodeParse.getInnerBusinessType(),
//                "sourceBusinessKey",epcPartCodeParse.getInnerBusinessKey(),
//                "operate", "编译",
//                "content", "数据中心编译代办",
//                "from_id", userId,
//                "to_id", users,
//                "processDefinitionName", "数据中心编译代办",
//                "formId", "/form/autoparts.epcPartCodeParse",
//                "api", "autoparts.epcPartNumberParse.findOne",
//                "checked", false
//        ));
//
//    }



    /***
     * 获取当前单据的所有抄送消息，并设为已查看
     */
    private void updateAllCarbonCopyMessage(EpcPartCodeParse epcPartCodeParse) {
        List<CarbonCopyMessage> carbonCopyMessageList = carbonCopyMessageRepository.findAll(JpaDsl.toCriteriaByEq(
                "sourceBusinessType", epcPartCodeParse.getInnerBusinessType(),
                "sourceBusinessKey", epcPartCodeParse.getInnerBusinessKey()
        ));

        // 循环设置为已查看
        carbonCopyMessageList.forEach(carbonCopyMessage -> {
            carbonCopyMessage.setChecked(true);
            carbonCopyMessageRepository.save(carbonCopyMessage);
        });
    }

    /***
     * 写编译历史操作信息
     */
    private void insertLogger(EpcPartCodeParse epcPartCodeParse, SimpleRequest request) {
        apesLoggerService.sendSynEvent("event:ir.logger.create", MapUtil.mapper("businessType", epcPartCodeParse.getInnerBusinessType(),
                "businessKey", epcPartCodeParse.getId(), "operate", " 编译",
                "workPostName",request.getSession() != null ? request.getSession().getAttribute("workPostName", String.class) : null,
                "operator_id", ((User)request.getCurrentUser()).getId()));
    }

}
